package com.zzyl.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.crypto.digest.BCrypt;
import cn.hutool.json.JSONUtil;
import com.zzyl.constant.CacheConstants;
import com.zzyl.dto.LoginDto;
import com.zzyl.entity.User;
import com.zzyl.enums.BasicEnum;
import com.zzyl.exception.BaseException;
import com.zzyl.mapper.ResourceMapper;
import com.zzyl.mapper.UserMapper;
import com.zzyl.properties.JwtTokenProperties;
import com.zzyl.service.LoginService;
import com.zzyl.utils.JwtUtil;
import com.zzyl.vo.LoginVo;
import com.zzyl.vo.UserVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
@Slf4j
public class LoginServiceImpl implements LoginService {

    @Autowired
    UserMapper userMapper;
    @Autowired
    ResourceMapper resourceMapper;
    @Autowired
    JwtTokenProperties jwtTokenProperties;


    @Override
    public UserVo login(LoginDto dto) {
        if (ObjectUtil.isEmpty(userMapper.selectByUsername(dto.getUsername()))) {
            throw new BaseException(BasicEnum.INCORRECT_PASSWORD);
        }
        User user = userMapper.selectByUsername(dto.getUsername());
        if (!BCrypt.checkpw(dto.getPassword(), user.getPassword())) {
            throw new BaseException(BasicEnum.INCORRECT_PASSWORD);
        }

        UserVo userVo = BeanUtil.toBean(user, UserVo.class);

        HashMap<String, Object> map = new HashMap<>();
        map.put("id",userVo.getId());
        String jwt = JwtUtil.createJWT(jwtTokenProperties.getSecretKey(),jwtTokenProperties.getTtl() , map);
        userVo.setUserToken(jwt);
        return userVo;
    }
}
